import { useRef, useState } from 'react';
import './PostcodeQuery.scss';
import { getZoneRateCode } from '@/services';
import { formatCurrency } from '@/utils/common';

const PostcodeQuery = ({ skuInfo }: { skuInfo: Obj }) => {
  const [postcodeResult, setPostcodeResult] = useState<any>('');
  const [inputCode, setInputCode] = useState<any>('');
  const [inQuery, setInQuery] = useState(false);
  const postcodeRef = useRef<HTMLInputElement>(null);
  const minLen = 4;

  const queryCodeAndRate = async (postcode: string, state: string = 'AU') => {
    setPostcodeResult(
      <div className="query-loading">
        <div className="loading-anim"></div>
        Loading...
      </div>
    );
    setInQuery(true);
    const codes =
      (await getZoneRateCode({ postcode, state }).catch(e => {
        void e;
      })) || null;
    const zone = codes?.[0]?.zone_rate_code;
    const rates = skuInfo?.zone_rates?.[zone?.toLowerCase()];
    const shippingFee: any = !isNaN(rates)
      ? rates >= 9999
        ? 'Undeliverable'
        : rates == 0
          ? 'Free Shipping'
          : formatCurrency(rates)
      : '';
    const res = shippingFee ? (
      <div className="query-result">
        <div>
          Zone: <span>{zone}</span>
        </div>
        <div>
          Shipping fee: <span>{shippingFee}</span>
        </div>
      </div>
    ) : (
      'No results.'
    );
    // console.log(codes, zone, rates);
    setPostcodeResult(res);
    setInQuery(false);
  };

  const handleQueryPostcode = () => {
    if (inQuery) return;
    const postcode = postcodeRef?.current?.value;
    if (!postcode || postcode.length < minLen) return;
    queryCodeAndRate(postcode);
  };
  const handlePostcodeChange = (e: any) => {
    setInputCode(e.currentTarget.value);
  };
  const handleKeyDown = (e: any) => {
    if (e.key === 'Enter') {
      handleQueryPostcode();
    }
  };

  return (
    <div className="content-infos-product-query">
      {postcodeResult && (
        <div className="content-infos-product-query-result">
          {postcodeResult}
        </div>
      )}
      <div className="content-infos-product-query-form">
        <label>
          <span>SKU</span>
          <input
            className="content-infos-product-query-input sku"
            type="text"
            value={skuInfo?.sku}
            disabled
          />
        </label>
        <label>
          <span>Postcode</span>
          <input
            className="content-infos-product-query-input"
            type="text"
            maxLength={6}
            ref={postcodeRef}
            onChange={handlePostcodeChange}
            onKeyDown={handleKeyDown}
          />
        </label>
        <button
          className="content-infos-product-query-button"
          onClick={handleQueryPostcode}
          disabled={inputCode.length < minLen}
        >
          Query
        </button>
      </div>
    </div>
  );
};

export default PostcodeQuery;
